<template>
  <div>
    <div
      ref="chart"
      :style="{ width: svgWidth + 'px', height: svgHeight + 'px' }"
    ></div>
    
  </div>
</template>

<script>
import * as d3 from "d3";

export default {
  data() {
    return {
      svgWidth: 400,
      svgHeight: 200,
      data: [],
      xScale: null,
      yScale: null,
      xAxis: null,
      yAxis: null,
      line: null,
      timer: null,
      isLessThanOneMinute: true,
    };
  },
  mounted() {
    this.createChart();
    this.startMonitoring();
  },
  beforeUnmount() {
    this.stopMonitoring();
  },
  methods: {
    createChart() {
      const svg = d3
        .select(this.$refs.chart)
        .append("svg")
        .attr("width", this.svgWidth)
        .attr("height", this.svgHeight);

      this.xScale = d3.scaleLinear().range([0, this.svgWidth]);

      this.yScale = d3.scaleLinear().domain([0, 1]).range([this.svgHeight, 0]);

      this.line = svg
        .append("path")
        .datum(this.data)
        .attr("fill", "none")
        .attr("stroke", "steelblue")
        .attr("stroke-width", 2);
    },
    startMonitoring() {
      this.timer = setInterval(() => {
        const newData = Math.random(); // 生成一个0到1之间的随机数

        this.data.push(newData);

        if (this.data.length > 3) {
          this.data.shift();

          if (this.isLessThanOneMinute) {
            this.isLessThanOneMinute = false;

            this.xScale.domain([0, this.data.length - 1]);
          }
        } else {
          this.xScale.domain([0, 60]);
        }

        this.line.attr(
          "d",
          d3
            .line()
            .x((d, i) => this.xScale(i))
            .y((d) => this.yScale(d))
            .curve(d3.curveLinear)
        );
      }, 1000); // 每秒更新一次
    },
    stopMonitoring() {
      clearInterval(this.timer);
    },
  },
};
</script>